﻿using System;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SocialKit.LightRest;

namespace SocialKit.SinaWeibo.Api.Extensions
{
    /// <summary>
    /// HTTP 响应消息扩展类。
    /// </summary>
    static class HttpResponseMessageExtensions
    {
        /// <summary>
        /// 读取 JSON 数据为指定的类型。
        /// </summary>
        /// <typeparam name="T">要转换的类型。</typeparam>
        /// <param name="response">HTTP 响应消息。</param>
        /// <returns></returns>
        public static T ReadJsonContent<T>(this HttpResponseMessage response)
        {
            if (response == null)
                return default(T);

            return JsonConvert.DeserializeObject<T>(response.ReadContentAsString());
        }

        /// <summary>
        /// 读取 JSON 数据。
        /// </summary>
        /// <param name="response">HTTP 响应消息。</param>
        /// <returns></returns>
        public static object ReadJsonContent(this HttpResponseMessage response)
        {
            if (response == null)
                return null;

            return JsonConvert.DeserializeObject(response.ReadContentAsString());
        }

        /// <summary>
        /// 确保响应不包含错误，否则抛出异常。
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public static HttpResponseMessage Ensure(this HttpResponseMessage response)
        {
            if (response.StatusCode != HttpStatusCode.OK)
            {
                var json = ReadJsonContent(response) as JToken;

                throw new SinaWeiboException(json.Value<string>("request"), json.Value<int>("error_code"), json.Value<string>("error"));
            }

            return response;
        }
    }
}